package com.task;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @Description: 用socket技术获得百度的网页内容
 */
public class SocketTest {

    public static void main(String[] args){
        String host = "www.baidu.com";
        int port = 80;
        String filePath = "f:/test/socket.txt";

        Socket socket = null;
        OutputStream os = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;

        InputStream is = null;
        BufferedReader br = null;

        BufferedWriter bufferedWriter = null;
        try {
            socket = new Socket(InetAddress.getByName(host), port);
            os = socket.getOutputStream();
            osw = new OutputStreamWriter(os);
            bw = new BufferedWriter(osw);
            //编辑请求头，也就是请求参数，这是最基本的 正常请求会带好多参数
            bw.write("GET / HTTP/1.1\r\n");
            bw.write("Connection: Keep-Alive\r\n");
            bw.write("Host: www.baidu.com\r\n");
            bw.write("Connection: Keep-Alive\r\n\r\n");
            bw.flush();
            socket.shutdownOutput();

            //获取 response 相应结果
            is = socket.getInputStream();
            br = new BufferedReader(new InputStreamReader(is));

            bufferedWriter = new BufferedWriter(new FileWriter(filePath));
            String str = null;
            while ((str = br.readLine()) != null) {
                bufferedWriter.write(str);
                bufferedWriter.newLine();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                bw.close();
                osw.close();
                os.close();
                bufferedWriter.flush();
                bufferedWriter.close();
                is.close();
                br.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }







    }

}
